package org.easymis.portal.modules.main.controller;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.easymis.commons.web.utils.R;
import org.easymis.commons.web.utils.StringUtils;
import org.easymis.portal.modules.main.service.MemberMng;
import org.easymis.portal.modules.main.service.OrganizeMng;
import org.easymis.portal.modules.system.entitys.mybatis.dto.Member;
import org.easymis.portal.modules.system.entitys.mybatis.dto.Organize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 前台会员注册Action
 */
@Controller
@RequestMapping("/register/")
public class RegisterAction {
	/**
	 * 会员中心模板
	 */
	public static final String TPLDIR_MEMBER = "member";
	public static final String REGISTER = "register";
	public static final String REGISTER_STEP2 = "register_step2";
	@Autowired
	private MemberMng memberMng;
	@Autowired
	private OrganizeMng organizeMng;
	/**
	 * @see 跳转注册页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public String input(HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) {
		String authenticityToken = StringUtils.makeUUID();
		model.put("authenticityToken", authenticityToken);
		session.setAttribute("authenticityToken", authenticityToken);
		String path = request.getContextPath();			
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
		model.put("base", basePath);
		
		return "register";
	}
	
	/**
	 * 传手机号和验证码进来，然后效验验证码，再次效验是否手机号用户已存在
	 * @return
	 */
	@RequestMapping(value = "zcone", method = RequestMethod.POST)
	@ResponseBody
	public R zcone(String mobile, String code,HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) {
		// 判断手机号和用户不能为空
		if (StringUtils.isEmpty(code)) {
			return new R().error("验证码不能为空！");
		}
		if (StringUtils.isEmpty(mobile)) {
			return new R().error("手机号不能为空！");
		}
		//判断code是否正确
		if (!code.equals("123456")) {
			return new R().error("验证码不正确！");
		}
		//判断手机号用户是否已存在
		if (!isNumLegal(mobile)) {
			return new R().error("手机号格式不正确！");
		}
		Member member = memberMng.findByMember(mobile);
		if (member != null) {
			return new R().error("用户已存在！");
		}
		//所有条件满足的情况下就可以注册了 start
		// 由于用户是用手机号或邮箱式注册，所以当前这步不能把手机号与邮箱存入数据库，先以session的方式暂存，并返回给用户实体
		Member memberxy = new Member();
		memberxy.setMobile(mobile);
		session.setAttribute("mobile", memberxy);
		return new R().ok();
		//return new R().ok("请走下一步流程！",memberxy);
	}
	
	/**
	 * 当通过
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "zctwo", method = RequestMethod.POST)
	public R input(Member member, HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) {
		// 再次确认手机号情况
		if (StringUtils.isEmpty(member.getMobile())) {
			return new R().error("手机号不能为空！");
		}
		//判断手机号用户是否已存在
		if (!isNumLegal(member.getMobile())) {
			return new R().error("手机号格式不正确！");
		}
		Member mber = memberMng.findByMember(member.getMobile());
		if (mber != null) {
			return new R().error("用户已存在！");
		}
		//所有条件满足的情况下就可以注册了 start
		// 由于用户是用手机号或邮箱式注册，所以当前这步不能把手机号与邮箱存入数据库，先以session的方式暂存，并返回给用户实体
		Member mb = (Member) session.getAttribute("mobile");
		if (!mb.getMobile().equals(member.getMobile())) {
			return new R().error("注册异常！");
		}
		
		// 正式的注册信息 start
		memberMng.saveRegisterMember(member);
		// 若返回boolean
//		if (!memberMng.saveRegisterMember(member)) {
//			return Result.ok("注册失败！");
//		}
		return new R().ok("注册成功！");
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "index", method = RequestMethod.POST)
	public String submit(String username, String email, String password, String captcha,
			String nextUrl, HttpServletRequest request, HttpServletResponse response, ModelMap model)
			throws IOException {
		return null;
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/organize/register", method = RequestMethod.POST)
	public String platformSubmit(String mobile, String email, String password, String orgName, String userName,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		return null;
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/signUpConfirm", method = RequestMethod.POST)
	public String signUpConfirm(String mobile, String email, String password, String orgName, String userName,HttpSession session,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		String pAuthenticityToken = request.getParameter("authenticityToken");
		String authenticityToken = request.getParameter("authenticityToken");
		if (StringUtils.isEmpty(pAuthenticityToken)||StringUtils.isEmpty(authenticityToken)||!pAuthenticityToken.equals(authenticityToken)) {
			//jsonApi = new JsonApi(2, "验证失败！！！");
		}
		authenticityToken = StringUtils.makeUUID();
		model.put("authenticityToken", authenticityToken);
		session.setAttribute("authenticityToken", authenticityToken);
		request.setAttribute("mobile", mobile);
		return "register_step2";
	}
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R save(Member member,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		R jsonApi = R.ok();
		String pAuthenticityToken = request.getParameter("authenticityToken");
		String authenticityToken = request.getParameter("authenticityToken");
		if (StringUtils.isEmpty(pAuthenticityToken)||StringUtils.isEmpty(authenticityToken)||!pAuthenticityToken.equals(authenticityToken)) {
			jsonApi = new R().error(2, "验证失败！！！");
		}
		// 再次确认手机号情况
		if (StringUtils.isEmpty(member.getCompanyName())) {
			jsonApi = new R().error(2, "团队名称为空！");
		}
		if (StringUtils.isEmpty(member.getName())) {
			jsonApi = new R().error(2, "姓名不能为空！");
		}
		if (StringUtils.isEmpty(member.getMobile())) {
			jsonApi = new R().error(2, "手机号不能为空！");
		}
		if (StringUtils.isEmpty(member.getPassword())) {
			jsonApi = new R().error(2, "密码不能为空！");
		}

		
		memberMng.saveRegisterMember(member);
		return jsonApi;
	}

	/**
	 * @see 获取验证码并发发送到手机端
	* @Title: forwordAddByAjax
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param request
	* @param @param response
	* @param @param model
	* @param @param session
	* @param @return    设定文件
	* @return Object    返回类型
	* @throws
	 */
	@RequestMapping(value = "buildValidateCode")
	@ResponseBody
	public R forwordAddByAjax(
			HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) {
		String mobile = request.getParameter("mobile");
		String userCaptcha = request.getParameter("userCaptcha");
		R jsonApi = new R().ok();		
		if (StringUtils.isEmpty(mobile)) {
			jsonApi = new R().error();
		} else {					
			int shortMessageValidateCode=(int)(Math.random() * 1000000);			
			session.setAttribute("shortMessageValidateCode",shortMessageValidateCode);
			System.out.println(shortMessageValidateCode);
			//调用短信接口发送验证码
			jsonApi = new R().ok();
		}
		return jsonApi;
	}
	
	/**
	 * 查询用户是否存在
	 * @param request
	 * @param session
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryMobile")
	@ResponseBody
	public Boolean forwardMobile(HttpServletRequest request, HttpSession session, String mobile) throws Exception {
		Member member = memberMng.findByMobile(mobile);
		if (member != null) {
			return false;
		}
		return true;
	}
	/**
	 * 检查验证码是否正确
	* @Title: checkUserCaptcha
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param request
	* @param @param session
	* @param @param userCaptcha
	* @param @return
	* @param @throws Exception    设定文件
	* @return Boolean    返回类型
	* @throws
	 */
	@RequestMapping(value = "checkUserCaptcha")
	@ResponseBody
	public Boolean checkUserCaptcha(HttpServletRequest request, HttpSession session, String userCaptcha) throws Exception {
		String validateCode =(String) session.getAttribute("validateCode");
		if(StringUtils.isEmpty(validateCode)||StringUtils.isEmpty(userCaptcha))
			return false;
		
		return validateCode.equals(userCaptcha.toUpperCase());

	}
	@RequestMapping(value = "checkShortMessage")
	@ResponseBody
	public Boolean checkShortMessage(HttpServletRequest request, HttpSession session, String shortMessage) throws Exception {
		String shortMessageValidateCode =session.getAttribute("shortMessageValidateCode").toString();
		if(StringUtils.isEmpty(shortMessage))
			return false;
		
		return shortMessageValidateCode.equals(shortMessage);

	}
	@RequestMapping(value = "checkOrganizeName")
	@ResponseBody
	public Boolean checkOrganizeName(HttpServletRequest request, HttpSession session, String orgName) throws Exception {
		if (orgName != null) {
			Organize organize = organizeMng.findByOrgName(orgName.trim());
			if (organize != null) {
				return false;
			}
		}
		return true;

	}
	/**
	 * 正则表达 手机号码由11位数字组成， 匹配格式：前三位固定格式+后8位任意数 此方法中前三位格式有： 13+任意数 15+除4的任意数
	 * 18+除1和4的任意数 17+除9的任意数 147
	 */
	private static boolean isNumLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}
}
